//package com.xiao.message.service.handler;
//
//import com.xiao.client.blade.dto.UserAccountVO;
//import com.xiao.client.blade.feign.BladeUserClient;
//import com.xiao.client.common.R;
//import com.xiao.client.common.feign.TencentClient;
//import com.xiao.message.service.dto.UserNotificationDto;
//import com.xiao.message.service.dto.front.SubscribeMessageResp;
//import com.xiao.message.service.dto.front.WechatMessageRequest;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.core.ExchangeTypes;
//import org.springframework.amqp.rabbit.annotation.*;
//import org.springframework.amqp.support.AmqpHeaders;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.messaging.handler.annotation.Header;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//import org.springframework.web.client.RestTemplate;
//
//import java.util.Map;
//import java.util.Objects;
//
///**
// * @author mingyuezheng
// * 微信订阅 通知
// */
//
//@Slf4j
//@Component
//@RabbitListener(bindings = @QueueBinding(
//        value = @Queue(value = "queue.message.notification.wechat", durable = "true", autoDelete = "true"),
//        exchange = @Exchange(value = "exchange.fanout.message.notification", type = ExchangeTypes.FANOUT)), ackMode = "MANUAL")
//public class WechatNotificationHandler {
//
//    private final TencentClient tencentClient;
//    private final RestTemplate restTemplate;
//    private final BladeUserClient bladeUserClient;
//    private final StringRedisTemplate redisTemplate;
//
//    @Value("${wechat.subscribeMessage.url:}")
//    private String url;
//    @Value("${wechat.subscribeMessage.state:}")
//    private String state;
//    @Value("${wechat.subscribeMessage.lang:}")
//    private String lang;
//
//    public WechatNotificationHandler(TencentClient tencentClient, RestTemplate restTemplate, BladeUserClient bladeUserClient, StringRedisTemplate stringRedisTemplate) {
//        this.tencentClient = tencentClient;
//        this.restTemplate = restTemplate;
//        this.bladeUserClient = bladeUserClient;
//        this.redisTemplate = stringRedisTemplate;
//    }
//
//    @RabbitHandler
//    public void send(UserNotificationDto notificationDto, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, com.rabbitmq.client.Channel channel) throws Exception {
//        log.info("wechat 消费：{}", notificationDto);
//        // 读取用户的openId。
//        R<UserAccountVO> userAccountVo = bladeUserClient.getUserOpenId(Long.parseLong(notificationDto.getUserId()));
//        if (!userAccountVo.isSuccess() || userAccountVo.getData() == null) {
//            // 获取用户信息失败。
//            log.error("获取用户信息失败。userId={}, message={}", notificationDto.getUserId(), userAccountVo.getMsg());
//            throw new RuntimeException("获取用户信息失败。");
//        }
//        if (CollectionUtils.isEmpty(notificationDto.getWechatTemplateArgs()) || Objects.isNull(notificationDto.getTemplateId()) || Objects.isNull(notificationDto.getWechatPageUrl())) {
//            return;
//        }
//        String userOpenId = userAccountVo.getData().getOpenId();
//        Map<String, Object> params = notificationDto.getWechatTemplateArgs();
//        WechatMessageRequest request = WechatMessageRequest.builder()
//                .data(params)
//                .page(notificationDto.getWechatPageUrl())
//                .templateId(notificationDto.getTemplateId())
//                .toUser(userOpenId)
//                .state(state)
//                .lang(lang)
//                .build();
//
//        HttpHeaders httpHeaders = null;
//        httpHeaders = new HttpHeaders();
//
//        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
//        httpHeaders.setContentType(type);
//
//        String accessToken = getAccessToken(false);
//        String address = url + "?access_token=" + accessToken;
//        log.info("请求微信token URL：{}", address);
//        SubscribeMessageResp subscribeMessageResp = restTemplate.postForObject(address, request, SubscribeMessageResp.class);
//        log.info("微信订阅返回：{}", subscribeMessageResp);
//
//        long code = subscribeMessageResp.getErrcode();
//        long errCode = 42001;
//        long errCode2 = 40001;
//        if (errCode == code || errCode2 == code) {
//            String accessToken2 = getAccessToken(true);
//            subscribeMessageResp = restTemplate.postForObject(url + "?access_token=" + accessToken2, request, SubscribeMessageResp.class);
//            log.info("微信订阅返回to：{}", subscribeMessageResp);
//        }
//
//        channel.basicAck(deliveryTag, false);
//
//    }
//
//    private String getAccessToken(boolean isRefreshAutoToken) {
//        if (isRefreshAutoToken){//refresh
//           return tencentClient.refreshAccessToken();
//        }
//        return tencentClient.getAccessToken();
//    }
//}
